<template>
  <a-upload
    name="article_img"
    list-type="picture-card"
    class="avatar-uploader"
    method="post"
    :show-upload-list="false"
    action="http://localhost:3002/article/article_img"
    :withCredentials='true'
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <div class="size">
      <a-icon :type="loading ? 'loading' : 'plus'" />
      点击此处添加图片
    </div>
  </a-upload>
</template>

<script>
export default {
  name: "UploadImg",
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    // 状态改变的时候
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        //   上传成功
        const response = info.file.response;
        if (response.avatar) {
          const avatar = response.avatar;
          this.loading = false;
          // 触发得到该图片
          this.$bus.$emit('article_img', avatar);
          this.$emit('showImg', avatar);
        }
      }
    },
    // 上传前要处理的
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        // 只能上传图片类型
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        // 大小不能超过2M
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
  .size {
    width: 21rem;
  }
}
</style>